'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  let body = event;
  if (event.body !== undefined) {
    try {
      body = JSON.parse(event.body);
    } catch (e) {
      return {
        success: false,
        message: '请求体 JSON 解析失败',
        error: e.message
      };
    }
  }

  try {
    const days = body.days || 7;
    const labels = [];
    const dateMap = {};

    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const yesterday = new Date(today.getTime() - 1 * 24 * 60 * 60 * 1000);

    const targetDays = [];
    for (let i = days; i >= 1; i--) {
      const date = new Date(yesterday.getTime() - (i - 1) * 24 * 60 * 60 * 1000);
      const dayStr = date.toISOString().slice(0, 10); // YYYY-MM-DD
      const label = `${('0' + (date.getMonth() + 1)).slice(-2)}/${('0' + date.getDate()).slice(-2)}`;
      labels.push(label);
      dateMap[dayStr] = 0;
      targetDays.push(dayStr);
    }

    const res = await db.collection('appoint_records')
      .where({
        day: db.command.in(targetDays)
      })
      .get();

    res.data.forEach(item => {
      if (typeof item.day === 'string' && dateMap.hasOwnProperty(item.day)) {
        dateMap[item.day]++;
      }
    });

    const data = Object.values(dateMap);

    return {
      success: true,
      result: {
        labels,
        data
      }
    };

  } catch (error) {
    console.error('图表数据查询失败:', error);
    return {
      success: false,
      message: '查询失败',
      error: error.message
    };
  }
};
